import uniCrazyRouter from 'uni-crazy-router'
import type { App } from 'vue'
import { gotoPage } from '@/common/utils'
import { allowList } from '@/router/routes'

export function setupRouter(app: App) {
  app.use(uniCrazyRouter)
}

uniCrazyRouter.beforeEach(async (to, from, next) => {
  console.log(to, from)
  if (to.jumpType === 'navigateBack' && to.url === 'pages/login/login' && from?.url !== 'pages/login/subpages/privacy') {
    await gotoPage('/pages/index/index', 'redirectTo')
    return
  }
  if (!allowList.includes(to.url)) {
    const REFRESH_TOKEN = uni.getStorageSync('REFRESH_TOKEN') ?? ''
    if (!REFRESH_TOKEN) {
      console.log('[路由拦截]', to.url)
      uniCrazyRouter.afterNotNext(() => {
        let toUrl = `/${to.url}`
        if (!!to.search) toUrl = `${toUrl}?${to.search}`
        const navigateOption = {
          url: '/pages/login/login',
          passedParams: {
            url: toUrl
          }
        }
        uni.navigateTo(navigateOption)
      })
      return
    }
  }
  next()
})

uniCrazyRouter.afterEach((to, from) => {
  // 逻辑代码
})

uniCrazyRouter.onError(async (to, from) => {
  // 逻辑代码
  if (to.jumpType === 'navigateBack') {
    await gotoPage('/pages/index/index', 'redirectTo')
  }
})
